/* eslint-disable @typescript-eslint/no-unsafe-return */
import { NextRequest, NextResponse } from 'next/server'
import { withAuth } from 'next-auth/middleware'
import createMiddleware from 'next-intl/middleware'
import { getToken } from 'next-auth/jwt'
import { routing } from '@/i18n/routing'
import isMobile from 'ismobilejs'

const publicPages = [
  '/',
  '/sign-in',
  '/sign-up',
  '/forget',
  '/category',
  '/product',
  '/search',
  '/cart',
]

const intlMiddleware = createMiddleware(routing)

const authMiddleware = withAuth((req) => intlMiddleware(req), {
  callbacks: {
    authorized: ({ token }) => token != null,
  },
  pages: {
    signIn: '/sign-in',
  },
})

// 判斷當前環境是mobile
function detectMobile(req: NextRequest): boolean {
  const userAgent = req.headers.get('user-agent') || ''
  return isMobile(userAgent).any
}

export default async function middleware(req: NextRequest) {
  const publicPathnameRegex = RegExp(
    `^(/(${routing.locales.join('|')}))?(${publicPages
      .flatMap((p) => (p === '/' ? ['', '/'] : p))
      .join('|')})(/[0-9]+)?$`, // 允許 `/category/:id` 但只匹配數字
    'i'
  )
  const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname)

  // **判斷是否為 Mobile，並設置 `cookie`**
  const isMobile = detectMobile(req)
  // 創建 Response
  let res = NextResponse.next()
  res.cookies.set('isMobile', isMobile ? 'true' : 'false', {
    path: '/',
    httpOnly: false, // 允許前端存取
  })

  if (isPublicPage) {
    res = intlMiddleware(req)
  } else {
    // 获取会话令牌
    const token = await getToken({ req })
    if (token) {
      req.headers.set('Authorization', `Bearer ${token}`)
    }
    res = (authMiddleware as any)(req)
  }

  return res
}

export const config = {
  // Match all pathnames except for
  // - … if they start with `/api`, `/trpc`, `/_next` or `/_vercel`
  // - … the ones containing a dot (e.g. `favicon.ico`)
  matcher: '/((?!api|trpc|_next|_vercel|.*\\..*).*)',
}
